package com.hadoop.mr.job;

import com.hadoop.mr.mapper.CommentMonthCountMapper;
import com.hadoop.mr.reducer.CommentMonthCountReducer;
import com.hadoop.mr.writable.CommentWritable;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.db.DBConfiguration;
import org.apache.hadoop.mapreduce.lib.db.DBOutputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;

import java.io.IOException;

/**
 * Created by Administrator on 2019/7/11.
 */
public class CommentMonthCountJob {
    public static Integer goodsId;

    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {

        try {
            if (args == null || args.length < 1) {
                System.err.println("Parameter Errors! Usage <inputPath...> ");
                System.exit(-1);
            }
            String input = args[0];
            // 读取配置文件
            Configuration conf = new Configuration();
            DBConfiguration.configureDB(conf, "com.mysql.jdbc.Driver",
                    "jdbc:mysql://192.168.31.43:3306/gator", "root", "tiger");

            Job job = Job.getInstance(conf, "typeCount");
            // 指定本类、mapper、reducer类
            job.setJarByClass(CommentMonthCountJob.class);
            job.setMapperClass(CommentMonthCountMapper.class);
            job.setReducerClass(CommentMonthCountReducer.class);
            // 指定 mapper 输出 key 和 value 类
            job.setMapOutputKeyClass(Text.class);
            job.setMapOutputValueClass(CommentWritable.class);
            // 指定 reducer 输出 key 和 value 类
            job.setOutputKeyClass(Text.class);
            job.setOutputValueClass(CommentWritable.class);
            // 参数: 分析文件路径
            FileInputFormat.addInputPath(job, new Path(input));
            //设置格式DBOutputFormat
            job.setOutputFormatClass(DBOutputFormat.class);

            // 输出到哪些表、字段
            DBOutputFormat.setOutput(job, "data_count", "add_time", "total_count", "goods_name", "goods_type");
            // 在 hadoop 中运行结果
            boolean flag = job.waitForCompletion(true);
            if (flag) {
                System.out.println("Job is complete!");
            } else {
                System.out.println("Job is fail!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void setGoodsId(Integer id) {
        if (goodsId == null || goodsId == 0) {
            goodsId = id;
        }
    }
}
